#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ota.h"
#include "firmware.h"
#include "bsp.h"
#include "public/errno.h"
#include "main.h"
#include "ota_ware.h"

#define BLE_TYPE    1           //蓝牙固件类型，对应AT+OTASTR中的类型
#define BLE_SIZE    496*1024    //蓝牙固件大小，固件最大大小
#define BLE_SAVE    1           //0：表示保存到内存，数据掉电丢失；1：表示保存到外部FLASH，数据掉电任然存在
#define BLE_ADDR    0x00001000  //数据保存地址，保存外部FLASH起始地址，包含64字节头部信息

static int check(unsigned int type, unsigned int size, unsigned int save, unsigned int addr)
{
    firmware_head_t head = {0};

    if (save == 0) {
        /* 从SDRAM中读取固件头 */
        memcpy(&head, (void *)addr, sizeof(firmware_head_t));
    }
    else {
        /* 从FLASH中读取固件头 */
        app_flash_read(sizeof(firmware_head_t), (uint8_t *)&head, 0);
    }

    /* 检查固件标记 */
    if (0 != memcmp(head.flag, FIRMWARE_FLAG_STR, strlen(FIRMWARE_FLAG_STR))) {
        return -EBFONT;
    }

    /* 检查固件类型*/
    if (head.file_type != FIRMWARE_TYPE_BLE) {
         return -EBADFD;
    }

    return 0;
}

static int update(unsigned int type, unsigned int size, unsigned int save, unsigned int addr)
{
    /* 重启之前，应答升级成功 */
    char result[33] = {'\0'};
    snprintf(result, sizeof(result), "+OTARES:%u,%u\r\n", type, 0);
    printf("%s", result);

    /* 延时等待发送完成 */
    unsigned int timestart = getms();
    while (getms() > timestart + 100) {}

    app_flash_flush();

    /* 重启系统 */
    //NVIC_SystemReset();

    return 0;
}

ota_firmware_xfa_t ota_firmware_ble_xfa = {
    .type = BLE_TYPE,
    .size = BLE_SIZE,
    .save = BLE_SAVE,
    .addr = BLE_ADDR,
    .check = check,
    .update = update,
};
OTA_WARE_REGISTER(BLE_TYPE, BLE_SIZE, BLE_SAVE, BLE_ADDR, check, update);
